package fr.janua.server;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.janua.client.LoginService;
import fr.janua.shared.UserDTO;

public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {
	private static final long serialVersionUID = -8607001757170078322L;


	@Override
	public UserDTO loginServer(String name, String password) {
		// validate username and password
		UserDTO user = new UserDTO();
		
		// store the user/session id
		storeUserInSession(user);

		return user;
	}

	@Override
	public UserDTO loginFromSessionServer() {
		return getUserAlreadyFromSession();
	}

	@Override
	public boolean changePassword(String name, String newPassword) {
		// change password logic
		return true;
	}

	@Override
	public void logout() {
		deleteUserFromSession();
	}

	private UserDTO getUserAlreadyFromSession() {
		UserDTO user = null;
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		Object userObj = session.getAttribute("user");
		if (userObj != null && userObj instanceof UserDTO) {
			user = (UserDTO) userObj;
		}
		return user;
	}

	private void storeUserInSession(UserDTO user) {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession(true);
		session.setAttribute("user", user);
	}

	private void deleteUserFromSession() {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		session.removeAttribute("user");
	}

}
